package org.esjsoftware.v2m.rim.proxy;

import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import org.esjsoftware.v2m.rim.util.ServiceLocator;

/**
 * 
 * @author Ernest
 *
 */
public class MessageStatusProxy extends Thread{
	
    private ObserverInterface _ourObserver;
    private String username;
    private String password;
    private String sourcePhoneNumber;
    private boolean _stopRequest = false;
    
    public MessageStatusProxy (String username, String password, String sourcePhoneNumber, ObserverInterface observer){
    	super();
    	this.username = username;
    	this.password = password;
    	this.sourcePhoneNumber = sourcePhoneNumber;
    	this._ourObserver = observer;
    }
    
    /**
     * stop is called if the processing should not continue.
     */
    public void stop() {
        // Tell our observer
        observerError(ObserverInterface.CANCELLED, "Network communicaation stopped.");
        _stopRequest = true; // Will no longer tell Observer anything
        this.interrupt(); // Give our Thread a kick
    }

    private void observerError(int errorCode, String errorMessage) {
        if ( !_stopRequest ) {
            _ourObserver.processError(errorCode, errorMessage);
        }
    }

    private void observerResponse(byte [] reply) {
        if ( !_stopRequest ) {
            _ourObserver.processResponse(reply);
        }
    }
    
    /**
     * Process the long running or blocking operation in this Thread
     * Update the Observer as required using
     * - processStatus, whenever desired
     * and then one of:
     * - processError, if there was a problem
     * - processResponse, if the data was obtained OK
     */
    public void run () {
    	boolean willFail = false; // false - will finshed OK, true - will fail!
		String result = "";
		String url = "http://vsp.pbxsms.com/api.php";
		HttpConnection http = null; 
		InputStream is = null; 
		OutputStream os = null;
		try {
			url = url + ServiceLocator.getContactionString();
			http =(HttpConnection)Connector.open(url); 
			http.setRequestMethod(HttpConnection.POST); 
			http.setRequestProperty("User-Agent", "Voice2Mobiles"); 
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
			os = http.openOutputStream(); 
			String params = "http=1&username=" + username + "&password=" + password + "&cmd=getstatus&source=" + sourcePhoneNumber; 
			os.write(params.getBytes()); 
			os.flush(); 
			
			StringBuffer messageSend = new StringBuffer(); 
			is = http.openDataInputStream(); 
			int chr; 
			while(!_stopRequest && (chr = is.read()) != -1) { 
				messageSend.append((char) chr); 
			} 
			result = messageSend.toString();
		} catch (Exception e) {
			stop();
		} finally {
			try {
				if(is != null) 
					is.close(); 
				if(os != null) 
					os.close(); 
				if(http != null) 
					http.close();
			} catch (Exception e) {
				
			}
		}
		
        //  Did we finish OK or badly
        if ( willFail ) {
            observerError(ObserverInterface.ERROR, "Failed");
        } else {
            observerResponse(result.getBytes());
        }

        // Make sure we do nothing else
        _stopRequest = true;
        _ourObserver = null;
    }
}
